package io.renren.modules.oa.websocket;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import io.renren.modules.oa.entity.OaPlanConfigEntity;
import io.renren.modules.oa.entity.OaPlanLogEntity;
import io.renren.modules.oa.redis.DingtalkRedis;

/**
 * 广告机登陆  APP Socket
 * @author Administrator
 *
 */
public class DingtalkSocket  extends WebSocketServer{
	
	public static Lock lock = new ReentrantLock();
	
	public static ConcurrentHashMap<Integer,WebSocket> socketMap = new ConcurrentHashMap<Integer,WebSocket>();
	
	public static ConcurrentHashMap<Integer,Long> userMap = new ConcurrentHashMap<Integer,Long>();
	
	public DingtalkSocket(int port) {
        super(new InetSocketAddress(port));
    }

    public DingtalkSocket(InetSocketAddress address) {
        super(address);
    }

 
    public void onOpen(WebSocket wsk, ClientHandshake handshake) {
        // ws连接的时候触发的代码
    	System.out.println("有连接加入"+wsk.hashCode());
    	socketMap.put(wsk.hashCode(), wsk);
    }

    
    public void onClose(WebSocket wsk, int code, String reason, boolean remote) {
        //断开连接时候触发代码
        System.out.println(reason+"连接断开");
        if(wsk != null){
	        if(socketMap.containsKey(wsk.hashCode())){
	        	 socketMap.remove(wsk.hashCode());
	        }
	        if(userMap.containsKey(wsk.hashCode())){
	        	userMap.remove(wsk.hashCode());
	        }
        }
    }
   
    
    public void onMessage(WebSocket wsk, String message) {
    	//有消息时触发的方法    	System.out.println(message+"有新消息");
    	//发送消息的方法
    	try {
    		
			JSONObject json = new JSONObject(message);
			int code = json.getInt("code");	
			
			switch (code) {
			case 100:	//心跳包
				System.out.println("心跳包:"+message);
				sendMessageString(wsk, "{\"code\":100,\"success\":\"OK\"}");
				break;
			case 1:	//初始化
				System.out.println("广告机初始化:"+message);
				Long merchantId = json.getLong("merchnatId");
				userMap.put(wsk.hashCode(),merchantId);   
				sendMessageString(wsk, DingtalkRedis.getAdInfo(merchantId));
				break;

			default:
				break;
			}
			
    	} catch (Exception e) {
			e.printStackTrace();
		}
    }


	public void onError(WebSocket wsk, Exception ex) {
    	//错误调用的方法  
        System.out.println("error");
        if(wsk != null){
        	 if(socketMap.containsKey(wsk.hashCode())){
             	socketMap.remove(wsk.hashCode());
             }
             if(userMap.containsKey(wsk.hashCode())){
             	 userMap.remove(wsk.hashCode());
             }
        }else{
        	 ex.printStackTrace();   
        }
    }
    
	/**
	 * 给用户发送信息
	 * @param merchantId
	 * @param text
	 */
	public static synchronized void sendAllUser(Long merchantId,String text){
		System.out.println("商户ID:" + merchantId + "=" + text);
		for(Integer key:userMap.keySet()){
			if(userMap.get(key).equals(merchantId)){
				//发送商户信息		
				sendMessageString(socketMap.get(key),text);  //向该商户下的所有用户发送消息;
				
			}
		}
	}
	
	
	 /**
     * 发送文本消息
     * @param wsk
     * @param text
     */
    public static void sendMessageString(WebSocket wsk,String text){
    	try{
    		lock.lock();
    		wsk.send(text);
    	}catch(Exception e){
    		e.printStackTrace();
    	}finally{
    		lock.unlock();
    	}   
    	
    }
    
    
}

